package com.ztesoft.web.taskgenerator.taskjob;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.core.cache.EhCacheService;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.DateUtils;
import com.ztesoft.web.common.DMSConstant;
import com.ztesoft.web.taskgenerator.db.po.DmTaskPO;
import com.ztesoft.web.taskgenerator.service.IDmTaskService;
@Service
public class DmTaskSubJob{
	
	 private static final ZTEsoftLogManager logger = ZTEsoftLogManager
	            .getLogger(DmTaskSubJob.class);
	
	@Autowired
	private IDmTaskService iDmTaskService;
	
	@Resource(name = "frameworkEhCacheService")
	private EhCacheService dmsCacheService;
	
	public void createSubTask(List<DmTaskPO> dmTaskPOLst){
		try {
			List<DmTaskPO> insertTaskLst = new ArrayList<DmTaskPO>();
			logger.debug("生成子任务实例start:"+dmTaskPOLst);
			for (DmTaskPO dmTaskPO : dmTaskPOLst) {
				//Integer state = DMSConstant.dataRestore.get(dmTaskPO.getDmPlanId());
				Integer state = (Integer) dmsCacheService.get("dmsCache", "dataRecovery_"+dmTaskPO.getDmPlanId());
				if(state==1 || state==2 || state ==4){
					logger.debug("生成子任务模块中的数据恢复状态为"+state);
					continue;
				}
				if ((int)dmTaskPO.getIsCheck() == 1) {
					continue;
				}
				//复制任务
				DmTaskPO dts = dmTaskPO.cloneBO();
				dts.setParentTaskId(dmTaskPO.getDmTaskId());//关联母任务
				dts.setName(getTaskName(dmTaskPO));//派生子任务名称 
				insertTaskLst.add(dts);
			}
			logger.debug("insertTaskLst"+insertTaskLst);
			if (insertTaskLst.size() > 0) {				
				iDmTaskService.addSubBatch(insertTaskLst);
				logger.debug("生成子任务实例end:");
			} else {
				logger.debug("审批拒绝生成任务");
			}
		} catch (BaseAppException e1) {
			logger.error(e1);
		}
	}
	
	
	
	/**
	 * 包装任务名称
	 * DM_PLAN.plan_name_日期_DM_PLAN_RELATION.group_nbr_派生_序号，第一次派生序号为1，之后递增
	 * @param dmTaskPO
	 * @return
	 */
	private String getTaskName(DmTaskPO dmTaskPO){
		StringBuffer sbName = new StringBuffer();//StingBuffer用于存放任务周期名称
		int len;
		String taskName;
		SimpleDateFormat sdf =  new SimpleDateFormat(DateUtils.STR_DATE_FORMAT_DAY_WITHOUT_SPLIT);//yyyy-MM 
		String s = Arrays.toString(dmTaskPO.getName().split("-"));
		Pattern p = Pattern.compile("派生");  
	    Matcher m = p.matcher(s); 
	    if(m.find()){
	    	len = Integer.parseInt(dmTaskPO.getName().substring(dmTaskPO.getName().lastIndexOf("-")+1))+1;
	    }else{
	    	len = 1;
	    }
		taskName = sbName.append(dmTaskPO.getPlanName()).append("-").
		append(sdf.format(new Date())).append("-").append(dmTaskPO.getGroupNbr()).append("-").
		append("派生").append("-").append(len).toString();
		return taskName;
	}
}
		
